// @Author EthanScriptOn
// @Desc
package extend_parser

import (
	"database/sql"
	"fmt"
	"gitee.com/fatzeng/srf_switch_expansion_package/extend_config"
	"gitee.com/fatzeng/srf_switch_stream_bridge/bridge"
	"gitee.com/fatzeng/srf_switch_stream_bridge/framework/actuator"
	"reflect"
)

type MysqlExecResponseParser struct {
}

func (m *MysqlExecResponseParser) Parse(ctx *actuator.SrfSwitchBridgeActuatorContext, config *bridge.BridgeConfig, response interface{}) (interface{}, error) {
	result, ok := response.(sql.Result)
	if !ok {
		return nil, fmt.Errorf("response is not sql.Result")
	}

	if !config.ResultType.AssignableTo(reflect.TypeOf(extend_config.MysqlExecResponse{})) {
		return nil, fmt.Errorf("result type is not MysqlExecResponse")
	}

	resValue := reflect.New(config.ResultType)
	instance := resValue.Interface()

	execResponse := instance.(*extend_config.MysqlExecResponse)

	affected, err := result.RowsAffected()
	if err != nil {
		return nil, err
	}
	execResponse.RowsAffected = affected
	lastId, err := result.LastInsertId()
	if err != nil {
		return nil, err
	}
	execResponse.LastInsertId = lastId
	return execResponse, nil
}
